package com.hoshiicloud.shxping.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.controller.BaseController;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.spu.ExtSpuTags;
import com.hoshiicloud.goods.param.sku.ProductManageQueryParam;
import com.hoshiicloud.goods.param.spu.ExtSpuQueryParam;
import com.hoshiicloud.market.entity.activities.Slideshow;
import com.hoshiicloud.market.entity.activities.param.SlideshowQueryParam;
import com.hoshiicloud.shxping.dto.ESSpuDTO;
import com.hoshiicloud.shxping.dto.ExtSpuDto;
import com.hoshiicloud.shxping.dto.ExtSpuTagsDto;
import com.hoshiicloud.shxping.dto.PlatStoreDTO;
import com.hoshiicloud.shxping.feign.*;
import com.hoshiicloud.shxping.param.GoodsBrowseRecordAddParam;
import com.hoshiicloud.shxping.param.GoodsDetailQueryParam;
import com.hoshiicloud.shxping.util.HtmlUtil;
import com.hoshiicloud.shxping.vo.ImagesVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author yangcheng
 * @version 1.0
 * @title: GoodsController
 * @description: 商品相关接口Controller
 * @date 2019/5/31 15:01
 * @mail maiboyc@163.com
 */
@Slf4j
@RestController
@RequestMapping("/goods")
@Api(value = "商品管理", tags = {"商品相关操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class GoodsController extends BaseController {

    // 商品图片统一前缀（暂时使用甲方提供的地址）
    @Value("${image.url}")
    private String url;

    // 商品微服务Service
    @Resource
    private GoodsFeignService goodsFeignService;

    // 营销微服务FeignClient
    @Resource
    private IMarketFeignService marketFeignService;

    // 用户微服务
    @Resource
    private IUserFeignService userFeignService;

    // 订单微服务Service
    @Resource
    private OrderFeignService orderFeignService;

    // ES微服务Service
    @Resource
    private IElasticSearchFeignService elasticSearchFeignService;

    // 获取首页banner图片
    @PostMapping("/getBanners")
    @ApiOperation(value = "获取首页banner图片", notes = "获取首页banner图片", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<Map<String,Object>>> getBanners(@RequestBody Slideshow param) {
        Response<List<Map<String,Object>>> rs;
        try {
            if (null != param.getCompanyId() && null != param.getPlatformId() && null != param.getStoreId()) {
                // 按店铺查找
                Response<List<Slideshow>> banner_rs = marketFeignService.listBannerInfo(param);
                if (null != banner_rs && banner_rs.getCode() == 200 && null != banner_rs.getData() && banner_rs.getData().size() > 0) {
                    List<Map<String,Object>> list = new ArrayList<>();
                    banner_rs.getData().forEach(item -> {
                        Map<String,Object> map = new HashMap<>();
                        map.put("id",item.getId());
                        map.put("companyId",item.getCompanyId());
                        map.put("platformId",item.getPlatformId());
                        map.put("storeId",item.getStoreId());
                        map.put("name",item.getName());
                        map.put("imageUrl",item.getImageUrl());
                        map.put("jumpType",item.getJumpType());
                        if (item.getJumpType() == 1) {
                            if (StringUtils.isNotEmpty(item.getJumpUrl())) {
                                Response<ExtSpuDto> fSpuResponse = goodsFeignService.getExtSpuById(Long.parseLong(item.getJumpUrl()));
                                if (fSpuResponse.getData().getStatus() == 1) { // 上架的商品才存
                                    map.put("jumpUrl",item.getJumpUrl());
                                } else {
                                    map.put("jumpUrl",null);
                                }
                            } else {
                                map.put("jumpUrl",null);
                            }
                        } else {
                            map.put("jumpUrl",StringUtils.isNotEmpty(item.getJumpUrl())?item.getJumpUrl():null);
                        }
                        map.put("status",item.getStatus());
                        list.add(map);
                    });
                    rs = Response.data(list);
                } else {
                    // 没有对应店铺的，找对应店铺的总店banner
                    Response<PlatStoreDTO> store_rs = userFeignService.queryById(param.getStoreId());
                    if (null != store_rs && store_rs.getCode() == 200 && null != store_rs.getData()) {
                        param.setStoreId(store_rs.getData().getParentId());
                        Response<List<Slideshow>> parent_banner_rs = marketFeignService.listBannerInfo(param);
                        if (null != parent_banner_rs && parent_banner_rs.getCode() == 200 && null != parent_banner_rs.getData() && parent_banner_rs.getData().size() > 0) {
                            List<Map<String,Object>> list = new ArrayList<>();
                            parent_banner_rs.getData().forEach(item -> {
                                Map<String,Object> map = new HashMap<>();
                                map.put("id",item.getId());
                                map.put("companyId",item.getCompanyId());
                                map.put("platformId",item.getPlatformId());
                                map.put("storeId",item.getStoreId());
                                map.put("name",item.getName());
                                map.put("imageUrl",item.getImageUrl());
                                map.put("jumpType",item.getJumpType());
                                if (item.getJumpType() == 1) {// 商品
                                    if (StringUtils.isNotEmpty(item.getJumpUrl())) {
                                        // 根据当前的jumpUrl(总店spuId)
                                        Response<ExtSpuDto> zSpuResponse = goodsFeignService.getExtSpuById(Long.parseLong(item.getJumpUrl()));
                                        if (null != zSpuResponse && zSpuResponse.getCode() == 200 && null != zSpuResponse.getData()) {
                                            // 查找分店spuId
                                            ExtSpuQueryParam spuQueryParam = new ExtSpuQueryParam();
                                            spuQueryParam.setStoreId(store_rs.getData().getId());
                                            spuQueryParam.setSpuId(zSpuResponse.getData().getSpuId());
                                            Response<Page<ExtSpuDto>> fSpuResponse = goodsFeignService.page(spuQueryParam);
                                            // 商品状态  0-档案 1-已上架 2-已下架
                                            if(fSpuResponse.getData().getRecords().get(0).getStatus() == 1){
                                                map.put("jumpUrl",fSpuResponse.getData().getRecords().get(0).getId());
                                            } else {
                                                map.put("jumpUrl",null);
                                            }
                                        } else {
                                            map.put("jumpUrl",null);
                                        }
                                    } else {
                                        map.put("jumpUrl",null);
                                    }
                                } else {
                                    map.put("jumpUrl",StringUtils.isNotEmpty(item.getJumpUrl())?item.getJumpUrl():null);
                                }
                                map.put("status",item.getStatus());
                                list.add(map);
                            });
                            rs = Response.data(list);
                        } else {
                            rs = Response.failed("没有找到总店对应的banner信息");
                        }
                    } else {
                        rs = Response.failed("没有找到对应的店铺信息");
                    }
                }
            } else {
                rs = Response.failed("非法请求，请求参数不对，必须包含租户ID、平台ID、店铺ID");
            }
        } catch (Exception e) {
            log.error("获取首页banner图片异常：" + e.getMessage());
            rs = Response.failed("获取首页banner图片异常：" + e.getMessage());
        }
        return rs;
    }

    /**
     * 商品列表
     *
     * @param param 查询参数
     * @return Response<IPage < ExtSkuDto>>
     */
    @PostMapping("/getGoodsList")
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String, Object>>> getSpusWithMiniPrice(@RequestBody ExtSpuQueryParam param) {
        Response<Page<Map<String, Object>>> rs;
        try {
            rs = goodsFeignService.getSpusWithMiniPrice(param);
            List<Long> spuIds = new ArrayList<>();
            if (null != rs && rs.getCode() == 200 && null != rs.getData()) {
                rs.getData().getRecords().forEach(item -> spuIds.add(Long.parseLong((String)item.get("id"))));
                // 标签
                Response<Map<Long,List<ExtSpuTags>>> tags = goodsFeignService.getBySpuIds(spuIds);
                // 购买数量
                Response<List<Map<String,Object>>> sales = orderFeignService.selectSalesCountGroupByStorePid(2);
                // 关注数
                Response<List<Map<String,Object>>> focus = orderFeignService.selectFocusCountGroupByBaseSpuId();
                // 循环查询到的商品列表，将标签、购买数量、关注数添加到记录上，同时去查询库存，然后返回前端
                for (Map<String, Object> map : rs.getData().getRecords()) {
                    // 加上标签数据
                    if (null != tags && tags.getCode() == 200 && null != tags.getData()) {
                        for (Long key: tags.getData().keySet()) {
                            if (map.get("id").equals(String.valueOf(key))) {
                                map.put("tags",tags.getData().get(key));
                            }
                        }
                    }
                    // 加上购买数量数据（所有店铺的销量）
                    if (null != sales && sales.getCode() == 200 && null != sales.getData() && sales.getData().size() > 0) {
                        for (Map<String,Object> temp: sales.getData()) {
                            if (map.get("base_spu_id").equals(String.valueOf(temp.get("base_spu_id")))) {
                                map.put("sales",temp.get("count"));
                            }
                        }
                    }
                    // 加上关注数量数据
                    if (null != focus && focus.getCode() == 200 && null != focus.getData()) {
                        for (Map<String,Object> temp1: focus.getData()) {
                            if (map.get("base_spu_id").equals(String.valueOf(temp1.get("base_spu_id")))) {
                                map.put("focusers",temp1.get("total_views"));
                            }
                        }
                    }
                    // 查询当前对应店铺的库存（判断当前店铺是否是分销店铺，如果是根据总店铺id和基础spuId去查询库存）
                    if(((Integer)map.get("is_distributor")) == 1) {
                        // 上级店铺相同baseSkuId的库存
                        ProductManageQueryParam manageQueryParam= new ProductManageQueryParam();
                        manageQueryParam.setStoreId(Long.valueOf(map.get("parent_store_id").toString()));
                        manageQueryParam.setBaseSkuId(Long.parseLong((String)map.get("base_sku_id")));
                        Response<List<ProductManage>> manageResponse = goodsFeignService.listProductManage(manageQueryParam);
                        map.put("quantity",manageResponse.getData().get(0).getQuantity());
                    }

                    // 如果没统计到数据，默认显示0
                    if (map.get("sales") == null) {
                        map.put("sales",0);
                    }
                    if (map.get("focusers") == null) {
                        map.put("focusers",0);
                    }
                    if (map.get("quantity") == null) {
                        map.put("quantity",0);
                    }

                    // 当前截单时间（现在默认为22:00）
                    map.put("endTime","22:00");

                    // 当前商品现在下单提货时间
                    if (map.get("receipt_interval").toString().equals("0") && null != map.get("receipt_date")) {
                        map.put("delivery_time", map.get("receipt_date"));
                    } else {
                        map.put("delivery_time", LocalDateTime.now().plusDays(Integer.parseInt(map.get("receipt_interval").toString())));
                    }

                }
                // 排序 如果商品有权重，按照权重排列，否则乱序
                Page<Map<String, Object>> page = rs.getData();
                List<Map<String, Object>> list = page.getRecords();
                //权重list
                List<Map<String, Object>> weightList = new ArrayList<>();
                //无序list
                List<Map<String, Object>> shuffleList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    if (Integer.parseInt((String) map.get("weight")) > 0) {
                        weightList.add(map);
                    } else {
                        shuffleList.add(map);
                    }
                }
                Collections.shuffle(shuffleList);
                weightList.addAll(shuffleList);
                page.setRecords(weightList);
                rs.setData(page);
            }
        } catch (Exception e) {
            log.error("查询商品列表异常" + "[" + e.getMessage() + "]");
            rs = Response.failed("查询商品列表异常" + e.getMessage());
        }
        return rs;
    }

    /**
     * 根据类目查询商品列表
     *
     * @param param 查询参数
     * @return Response<Page < Map < String, Object>>>
     */
    @PostMapping("/getGoodsListByCategoryId")
    @ApiOperation(value = "根据类目查询商品列表", notes = "根据类目查询商品列表", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Page<Map<String, Object>>> getSpusByStoreIdAndCategoryId(@RequestBody ExtSpuQueryParam param) {
        Response<Page<Map<String, Object>>> rs;
        try {
            rs = goodsFeignService.getSpusByStoreIdAndCategoryId(param);
            if (null != rs && rs.getCode() == 200 && null != rs.getData()) {
                for (Map<String, Object> map : rs.getData().getRecords()) {
                    Response<List<ExtSpuTagsDto>> rs_tags = goodsFeignService.getTagsBySpuId(Long.parseLong((String) map.get("id")));
                    map.put("tags", rs_tags.getData());
                }

                //如果商品有权重，按照权重排列，否则乱序
                Page<Map<String, Object>> page = rs.getData();

                List<Map<String, Object>> list = page.getRecords();

                //权重list
                List<Map<String, Object>> weightList = new ArrayList<>();
                //无序list
                List<Map<String, Object>> shuffleList = new ArrayList<>();

                for (Map<String, Object> map : list) {

                    if (Integer.parseInt((String) map.get("weight")) > 0) {
                        weightList.add(map);
                    } else {
                        shuffleList.add(map);
                    }
                }

                Collections.shuffle(shuffleList);

                weightList.addAll(shuffleList);

                page.setRecords(weightList);

                rs.setData(page);

            }
        } catch (Exception e) {
            log.error("根据类目查询商品列表异常" + "[" + e.getMessage() + "]");
            rs = Response.failed("根据类目查询商品列表异常" + e.getMessage());
        }
        return rs;
    }

    /**
     * 获取商品详情
     *
     * @param param 查询参数
     * @return Response<Map < String, Object>>
     */
    @PostMapping("/getGoodsDetail")
    @ApiOperation(value = "获取商品详情", notes = "获取商品详情")
    public Response<Map<String, Object>> getGoodsDetail(@RequestBody GoodsDetailQueryParam param) {
        Response<Map<String, Object>> rs = null;
        try {
            Response<List<Map<String, Object>>> goodsDetails = goodsFeignService.getGoodsDetail(Long.parseLong(param.getId()));
            // 购买数量
            Response<List<Map<String,Object>>> sales = orderFeignService.selectSalesCountGroupByStorePid(2);
            if (null != goodsDetails && goodsDetails.getCode() == 200 && null != goodsDetails.getData()) {
                for (Map<String, Object> map : goodsDetails.getData()) {
                    Map<String, Object> temp = JSON.parseObject((String) map.get("spec"), Map.class);
                    if (null != temp.get("spec1")) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("spuId", map.get("spu_id"));
                        data.put("skuId", map.get("sku_id"));
                        data.put("title", map.get("title"));
                        data.put("description", getDescImages((String) map.get("description")));
                        data.put("categories", getCategoriesOrTags((String) map.get("categories")));
                        Response<List<ExtSpuTagsDto>> rs_tags = goodsFeignService.getTagsBySpuId(Long.parseLong((String) map.get("spu_id")));
                        data.put("tags", rs_tags.getData());
                        data.put("minPrice", map.get("minPrice"));
                        data.put("maxPrice", map.get("maxPrice"));
                        data.put("spec", map.get("spec"));
                        data.put("images", getImages((String) map.get("images")));
                        data.put("storeId", map.get("store_id"));
                        //data.put("sales", map.get("sales"));
                        // 加上购买数量数据（所有店铺的销量）
                        if (null != sales && sales.getCode() == 200 && null != sales.getData() && sales.getData().size() > 0) {
                            for (Map<String,Object> sale: sales.getData()) {
                                if (map.get("spu_id").equals(String.valueOf(sale.get("spu_id")))) {
                                    data.put("sales",sale.get("count"));
                                }
                            }
                        }
                        data.put("focusers", map.get("focusers"));
                        data.put("quantity", map.get("quantity"));
                        data.put("receiptInterval",map.get("receipt_interval"));
                        // 当前截单时间（现在默认为22:00）
                        data.put("endTime","22:00");
                        // 当前商品现在下单提货时间
                        if (map.get("receipt_interval").toString().equals("0") && null != map.get("receipt_date")) {
                            data.put("deliveryTime", map.get("receipt_date"));
                        } else {
                            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                            data.put("deliveryTime", dtf.format(LocalDateTime.now().plusDays(Integer.parseInt(map.get("receipt_interval").toString()))));
                        }
                        rs = Response.data(data);
                        break;
                    }
                }

                // 用户不为空添加商品浏览记录
                if (param.getUserId() != null) {
                    List<Map<String, Object>> list = goodsDetails.getData();
                    if (list.size() > 0) {
                        Map<String, Object> map = list.get(0);
                        GoodsBrowseRecordAddParam goodsBrowseRecordAddParam = new GoodsBrowseRecordAddParam();
                        goodsBrowseRecordAddParam.setChannel(3L);
                        goodsBrowseRecordAddParam.setSpuId(Long.parseLong(map.get("spu_id").toString()));
                        goodsBrowseRecordAddParam.setSkuId(Long.parseLong(map.get("sku_id").toString()));
                        goodsBrowseRecordAddParam.setStoreId(Long.parseLong(map.get("store_id").toString()));
                        goodsBrowseRecordAddParam.setUserId(Long.parseLong(param.getUserId()));
                        orderFeignService.add(goodsBrowseRecordAddParam);
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取商品详情异常", e);
            rs = Response.failed("获取商品详情异常" + e.getMessage());
        }
        return rs;
    }

    /**
     * 根据spuId获取标签信息
     *
     * @param spuId 商品SPU主键
     * @return Response<List < ExtSpuTagsDto>>
     */
    @GetMapping("/getTagsBySpuId/{spuId}")
    @ApiOperation(value = "根据spuId获取标签信息", notes = "根据spuId获取标签信息")
    public Response<List<ExtSpuTagsDto>> getTagsBySpuId(@PathVariable("spuId") Long spuId) {
        Response<List<ExtSpuTagsDto>> rs;
        try {
            rs = goodsFeignService.getTagsBySpuId(spuId);
        } catch (Exception e) {
            log.error("根据spuId获取标签信息异常" + "[" + e.getMessage() + "]");
            rs = Response.failed("根据spuId获取标签信息异常" + e.getMessage());
        }
        return rs;
    }

    /**
     * 根据标签ID获取标签信息
     *
     * @param id ID
     * @return Response<ExtSpuTagsDto>
     */
    @GetMapping("/getTagById/{id}")
    @ApiOperation(value = "根据ID获取标签信息", notes = "根据ID获取标签信息")
    public Response<ExtSpuTagsDto> getTagById(@PathVariable("id") Long id) {
        Response<ExtSpuTagsDto> rs;
        try {
            rs = goodsFeignService.getTagById(id);
        } catch (Exception e) {
            log.error("根据ID获取标签信息异常" + "[" + e.getMessage() + "]");
            rs = Response.failed("根据ID获取标签信息异常" + e.getMessage());
        }
        return rs;
    }

    /**
     * 首页Banner跳转功能
     * @param param 参数
     * @return Response<Map<String, Object>>
     */
    @PostMapping("/HomeBannerJump")
    @ApiOperation(value = "首页Banner跳转功能", notes = "首页Banner跳转功能")
    public Response<Map<String, Object>> HomeBannerJump(@RequestBody SlideshowQueryParam param) {
        Response<Map<String, Object>> rs;
        switch (param.getJumpType()){
            // 商品
            case 1:
                // 根据当前店铺和配置的spuId查找对应商品信息
                ExtSpuQueryParam spuQueryParam = new ExtSpuQueryParam();
                spuQueryParam.setSpuId(param.getJumpUrl());
                spuQueryParam.setStoreId(param.getCurStoreId());
                Response<Page<ExtSpuDto>> spuResponse = goodsFeignService.page(spuQueryParam);
                if (null != spuResponse && spuResponse.getCode() == 200 && null != spuResponse.getData()) {
                    Response<List<Map<String, Object>>> goodsDetails = goodsFeignService.getGoodsDetail(spuResponse.getData().getRecords().get(0).getId());
                    if (null != goodsDetails && goodsDetails.getCode() == 200 && null != goodsDetails.getData()) {
                        for (Map<String, Object> map : goodsDetails.getData()) {
                            Map<String, Object> temp = JSON.parseObject((String) map.get("spec"), Map.class);
                            if (null != temp.get("spec1")) {
                                Map<String, Object> data = new HashMap<>();
                                data.put("spuId", map.get("spu_id"));
                                data.put("skuId", map.get("sku_id"));
                                data.put("title", map.get("title"));
                                data.put("description", getDescImages((String) map.get("description")));
                                data.put("categories", getCategoriesOrTags((String) map.get("categories")));
                                Response<List<ExtSpuTagsDto>> rs_tags = goodsFeignService.getTagsBySpuId(Long.parseLong((String) map.get("spu_id")));
                                data.put("tags", rs_tags.getData());
                                data.put("minPrice", map.get("minPrice"));
                                data.put("maxPrice", map.get("maxPrice"));
                                data.put("spec", map.get("spec"));
                                data.put("images", getImages((String) map.get("images")));
                                data.put("storeId", map.get("store_id"));
                                data.put("sales", map.get("sales"));
                                data.put("focusers", map.get("focusers"));
                                data.put("quantity", map.get("quantity"));
                                data.put("receiptInterval",map.get("receipt_interval"));
                                // 当前截单时间（现在默认为22:00）
                                data.put("endTime","22:00");
                                // 当前商品现在下单提货时间
                                if (map.get("receipt_interval").toString().equals("0") && null != map.get("receipt_date")) {
                                    data.put("deliveryTime", map.get("receipt_date"));
                                } else {
                                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    data.put("deliveryTime", dtf.format(LocalDateTime.now().plusDays(Integer.parseInt(map.get("receipt_interval").toString()))));
                                }
                                rs = Response.data(data);
                                break;
                            }
                        }

                        // 用户不为空添加商品浏览记录
                        if (param.getUserId() != null) {
                            List<Map<String, Object>> list = goodsDetails.getData();
                            if (list.size() > 0) {
                                Map<String, Object> map = list.get(0);
                                GoodsBrowseRecordAddParam goodsBrowseRecordAddParam = new GoodsBrowseRecordAddParam();
                                goodsBrowseRecordAddParam.setChannel(3L);
                                goodsBrowseRecordAddParam.setSpuId(Long.parseLong(map.get("spu_id").toString()));
                                goodsBrowseRecordAddParam.setSkuId(Long.parseLong(map.get("sku_id").toString()));
                                goodsBrowseRecordAddParam.setStoreId(Long.parseLong(map.get("store_id").toString()));
                                goodsBrowseRecordAddParam.setUserId(param.getUserId());
                                orderFeignService.add(goodsBrowseRecordAddParam);
                            }
                        }
                    }
                } else {
                    rs = Response.failed("没有查询到跳转相应的信息");
                }
            // 其他
            case 2:
                // Response<PlatStoreDTO> storeDTOS = userFeignService.queryById(param.getCurStoreId());
                // rs = Response.data(BeanUtils.beanToMap(storeDTOS.getData()));
                rs = Response.failed("当前配置的图片跳转功能正在开发中");
            // 默认
            default:
                rs = Response.failed("当前配置的图片跳转功能正在开发中！");
        }
        return rs;
    }

    /**
     * 从ES查询商品列表
     * @param storeId   店铺ID
     * @param pageNum   页码
     * @param pageSize  每页记录数
     * @return Response<org.springframework.data.domain.Page<ESSpuDTO>>
     */
    @GetMapping("/getListFromEs")
    @ApiOperation(value = "从ES查询商品列表", notes = "从ES查询商品列表")
    public Response<Page<Map<String,Object>>> getListFromEs(@RequestParam("storeId") Long storeId, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Response<Page<Map<String,Object>>> rs;
        try {
            Response<Page<ESSpuDTO>> spus = Response.data(elasticSearchFeignService.list(storeId,pageNum,pageSize));
            List<Long> spuIds = new ArrayList<>();
            if (null != spus && spus.getCode() == 200 && null != spus.getData()) {
                spus.getData().getRecords().forEach(item -> spuIds.add(item.getId()));
                // 标签
                Response<Map<Long,List<ExtSpuTags>>> tags = goodsFeignService.getBySpuIds(spuIds);
                // 购买数量
                Response<List<Map<String,Object>>> sales = orderFeignService.selectSalesCountGroupByStorePid(2);
                // 关注数
                Response<List<Map<String,Object>>> focus = orderFeignService.selectFocusCountGroupByBaseSpuId();
                Page<Map<String,Object>> page = new Page<>();
                page.setTotal(spus.getData().getTotal());
                page.setPages(spus.getData().getPages());
                page.setSize(spus.getData().getSize());
                page.setCurrent(spus.getData().getCurrent());
                List<Map<String,Object>> list = new ArrayList<>();
                spus.getData().getRecords().forEach(item -> {
                    Map<String,Object> map = new HashMap<>();
                    map.put("store_id",item.getStoreId());
                    map.put("company_id",item.getCompanyId());
                    map.put("maket_price",item.getMaketPrice());
                    map.put("spu_image",item.getSpuImage());
                    map.put("weight",item.getWeight());
                    map.put("sku_id",item.getSkuId());
                    map.put("title",item.getTitle());
                    map.put("parent_store_id",item.getParentStoreId());
                    map.put("sale_price",item.getSalePrice());
                    map.put("base_spu_id",item.getBaseSpuId());
                    map.put("base_sku_id",item.getBaseSkuId());
                    map.put("platform_id",item.getPlatformId());
                    map.put("is_distributor",item.getIsDistributor());
                    map.put("id",item.getId());
                    map.put("receipt_interval",item.getReceiptInterval());
                    map.put("receipt_date",item.getReceiptDate());
                    map.put("sales_category_id",item.getSalesCategoryId());
                    // 加上标签数据
                    if (null != tags && tags.getCode() == 200 && null != tags.getData()) {
                        for (Long key: tags.getData().keySet()) {
                            if (item.getId().equals(key)) {
                                map.put("tags",tags.getData().get(key));
                            }
                        }
                    }
                    // 加上购买数量数据（所有店铺的销量）
                    if (null != sales && sales.getCode() == 200 && null != sales.getData() && sales.getData().size() > 0) {
                        for (Map<String,Object> temp: sales.getData()) {
                            if (null != temp.get("base_spu_id")) {
                                if (item.getBaseSpuId().equals(Long.parseLong(temp.get("base_spu_id").toString()))) {
                                    map.put("sales",temp.get("count"));
                                }
                            }
                        }
                    }
                    // 加上关注数量数据
                    if (null != focus && focus.getCode() == 200 && null != focus.getData()) {
                        for (Map<String,Object> temp1: focus.getData()) {
                            if (null != temp1.get("base_spu_id")) {
                                if (item.getBaseSpuId().equals(Long.parseLong(temp1.get("base_spu_id").toString()))) {
                                    map.put("focusers",temp1.get("total_views"));
                                }
                            }
                        }
                    }
                    // 查询当前对应店铺的库存（判断当前店铺是否是分销店铺，如果是根据总店铺id和基础spuId去查询库存）
                    if(item.getIsDistributor() == 1) {
                        // 上级店铺相同baseSkuId的库存
                        ProductManageQueryParam manageQueryParam= new ProductManageQueryParam();
                        manageQueryParam.setStoreId(item.getParentStoreId());
                        manageQueryParam.setBaseSkuId(item.getBaseSkuId());
                        Response<List<ProductManage>> manageResponse = goodsFeignService.listProductManage(manageQueryParam);
                        map.put("quantity",manageResponse.getData().get(0).getQuantity());
                    }

                    // 如果没统计到数据，默认显示0
                    if (map.get("sales") == null) {
                        map.put("sales",0);
                    }
                    if (map.get("focusers") == null) {
                        map.put("focusers",0);
                    }
                    if (map.get("quantity") == null) {
                        map.put("quantity",0);
                    }
                    map.put("endTime","22:00");
                    // 当前商品现在下单提货时间
                    if (item.getReceiptInterval() == 0 && null != item.getReceiptDate()) {
                        map.put("delivery_time", map.get("receipt_date"));
                    } else {
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        map.put("delivery_time", dtf.format(LocalDateTime.now().plusDays(item.getReceiptInterval())));
                    }
                    list.add(map);
                });
                page.setRecords(list);
                rs = Response.data(page);
            } else {
                rs = Response.failed("没有查询到商品信息");
            }
        } catch (Exception e) {
            log.error("从ES查询商品列表异常："+e.getMessage());
            rs = Response.failed("从ES查询商品列表异常："+e.getMessage());
        }
        return rs;
    }

    /**
     * 从ES根据标题搜索商品列表
     * @param keyword   关键字
     * @param pageNum   页码
     * @param pageSize  每页记录数
     * @return Response<org.springframework.data.domain.Page<ESSpuDTO>>
     */
    @GetMapping("/searchListFromEs")
    @ApiOperation(value = "从ES根据标题搜索商品列表", notes = "从ES根据标题搜索商品列表")
    public Response<Page<Map<String,Object>>> searchListFromEs(@RequestParam("keyword") String keyword, @RequestParam("storeId") Long storeId, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        Response<Page<Map<String,Object>>> rs;
        try {
            Response<Page<ESSpuDTO>> spus = Response.data(elasticSearchFeignService.search(keyword,storeId,pageNum,pageSize));
            List<Long> spuIds = new ArrayList<>();
            if (null != spus && spus.getCode() == 200 && null != spus.getData()) {
                spus.getData().getRecords().forEach(item -> spuIds.add(item.getId()));
                // 标签
                Response<Map<Long,List<ExtSpuTags>>> tags = goodsFeignService.getBySpuIds(spuIds);
                // 购买数量
                Response<List<Map<String,Object>>> sales = orderFeignService.selectSalesCountGroupByStorePid(2);
                // 关注数
                Response<List<Map<String,Object>>> focus = orderFeignService.selectFocusCountGroupByBaseSpuId();
                Page<Map<String,Object>> page = new Page<>();
                page.setTotal(spus.getData().getTotal());
                page.setPages(spus.getData().getPages());
                page.setSize(spus.getData().getSize());
                page.setCurrent(spus.getData().getCurrent());
                List<Map<String,Object>> list = new ArrayList<>();
                spus.getData().getRecords().forEach(item -> {
                    Map<String,Object> map = new HashMap<>();
                    map.put("store_id",item.getStoreId());
                    map.put("company_id",item.getCompanyId());
                    map.put("maket_price",item.getMaketPrice());
                    map.put("spu_image",item.getSpuImage());
                    map.put("weight",item.getWeight());
                    map.put("sku_id",item.getSkuId());
                    map.put("title",item.getTitle());
                    map.put("parent_store_id",item.getParentStoreId());
                    map.put("sale_price",item.getSalePrice());
                    map.put("base_spu_id",item.getBaseSpuId());
                    map.put("base_sku_id",item.getBaseSkuId());
                    map.put("platform_id",item.getPlatformId());
                    map.put("is_distributor",item.getIsDistributor());
                    map.put("id",item.getId());
                    map.put("receipt_interval",item.getReceiptInterval());
                    map.put("receipt_date",item.getReceiptDate());
                    map.put("sales_category_id",item.getSalesCategoryId());
                    // 加上标签数据
                    if (null != tags && tags.getCode() == 200 && null != tags.getData()) {
                        for (Long key: tags.getData().keySet()) {
                            if (item.getId().equals(key)) {
                                map.put("tags",tags.getData().get(key));
                            }
                        }
                    }
                    // 加上购买数量数据（所有店铺的销量）
                    if (null != sales && sales.getCode() == 200 && null != sales.getData() && sales.getData().size() > 0) {
                        for (Map<String,Object> temp: sales.getData()) {
                            if (null != temp.get("base_spu_id")) {
                                if (item.getBaseSpuId().equals(Long.parseLong(temp.get("base_spu_id").toString()))) {
                                    map.put("sales",temp.get("count"));
                                }
                            }
                        }
                    }
                    // 加上关注数量数据
                    if (null != focus && focus.getCode() == 200 && null != focus.getData()) {
                        for (Map<String,Object> temp1: focus.getData()) {
                            if (null != temp1.get("base_spu_id")) {
                                if (item.getBaseSpuId().equals(Long.parseLong(temp1.get("base_spu_id").toString()))) {
                                    map.put("focusers",temp1.get("total_views"));
                                }
                            }
                        }
                    }
                    // 查询当前对应店铺的库存（判断当前店铺是否是分销店铺，如果是根据总店铺id和基础spuId去查询库存）
                    if(item.getIsDistributor() == 1) {
                        // 上级店铺相同baseSkuId的库存
                        ProductManageQueryParam manageQueryParam= new ProductManageQueryParam();
                        manageQueryParam.setStoreId(item.getParentStoreId());
                        manageQueryParam.setBaseSkuId(item.getBaseSkuId());
                        Response<List<ProductManage>> manageResponse = goodsFeignService.listProductManage(manageQueryParam);
                        map.put("quantity",manageResponse.getData().get(0).getQuantity());
                    }

                    // 如果没统计到数据，默认显示0
                    if (map.get("sales") == null) {
                        map.put("sales",0);
                    }
                    if (map.get("focusers") == null) {
                        map.put("focusers",0);
                    }
                    if (map.get("quantity") == null) {
                        map.put("quantity",0);
                    }
                    map.put("endTime","22:00");
                    // 当前商品现在下单提货时间
                    if (item.getReceiptInterval() == 0 && null != item.getReceiptDate()) {
                        map.put("delivery_time", map.get("receipt_date"));
                    } else {
                        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        map.put("delivery_time", dtf.format(LocalDateTime.now().plusDays(item.getReceiptInterval())));
                    }
                    list.add(map);
                });
                page.setRecords(list);
                rs = Response.data(page);
            } else {
                rs = Response.failed("没有查询到商品信息");
            }
        } catch (Exception e) {
            log.error("从ES根据标题搜索商品列表异常："+e.getMessage());
            rs = Response.failed("从ES根据标题搜索商品列表异常："+e.getMessage());
        }
        return rs;
    }

    /**
     * 转换商品描述图
     *
     * @param description 商品描述
     * @return List<ImagesVO>
     */
    private List<ImagesVO> getDescImages(String description) {
        List<ImagesVO> list;
        String[] image;
        if (StringUtils.isNotEmpty(description)) {
            list = new ArrayList<>();
            if (description.indexOf("img") > -1) {
                image = HtmlUtil.getImgs(description);
            } else {
                image = description.split(",");
            }
            if (image.length > 0) {
                for (String s : image) {
                    if (s.indexOf(".jpg") > -1 || s.indexOf(".png") > -1 || s.indexOf(".JPG") > -1) {// 图片
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(0);
                        list.add(imagesVO);
                    } else {// 视频
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(1);
                        list.add(imagesVO);
                    }
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 转换商品轮播图
     *
     * @param images 轮播图图片ID字符串
     * @return List<ImagesVO>
     */
    private List<ImagesVO> getImages(String images) {
        List<ImagesVO> list;
        if (StringUtils.isNotEmpty(images)) {
            list = new ArrayList<>();
            String[] image = images.split(",");
            if (image.length > 0) {
                for (String s : image) {
                    if (s.indexOf(".jpg") > -1 || s.indexOf(".png") > -1 || s.indexOf(".JPG") > -1) {// 图片
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(0);
                        list.add(imagesVO);
                    } else {// 视频
                        ImagesVO imagesVO = new ImagesVO();
                        imagesVO.setUrl(s);
                        imagesVO.setType(1);
                        list.add(imagesVO);
                    }
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return list;
    }

    /**
     * 转换类目或标签
     *
     * @param categories
     * @return List<String>
     */
    private List<String> getCategoriesOrTags(String categories) {
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(categories)) {
            String[] temp = categories.split(",");
            for (String s : temp) {
                list.add(s);
            }
        }
        return list;
    }

}
